package com.fishery.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fishery.authority.entity.*;
import com.fishery.authority.mapper.FunctionMapper;
import com.fishery.authority.mapper.RoleMapper;
import com.fishery.authority.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.authority.utils.SecurityContextUtil;
import com.fishery.entity.GlobalException;
import com.fishery.entity.Result;
import com.fishery.entity.StatusCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 711
 * @since 2021-01-13
 */
@Service
public class FunctionServiceImpl extends ServiceImpl<FunctionMapper, Function> implements FunctionService {

    @Autowired
    private RoleService roleService;

    @Autowired
    private FunctionRoleService functionRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private BaseRoleFunctionService baseRoleFunctionService;

    @Autowired
    private FunctionMapper functionMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 查询所有权限
     *
     * @return
     */
    @Override
    public List<Function> queryAllFunction() {
        //1 查询权限表所有数据
        QueryWrapper<Function> wrapper = new QueryWrapper<>();
        List<Function> functionList = baseMapper.selectList(wrapper);
        return functionList;
    }

    /**
     * 权限分级
     *
     * @param functionList
     * @return
     */
    @Override
    public List<FunctionParent> grand(List<Function> functionList) {

        // 保存一级权限的集合
        List<FunctionParent> oneLevelFunctionList = new ArrayList<>();

        // 添加一级权限
        for (Function function : functionList) {
            // pid为空的即为第一级权限
            if (function.getParentId() == null) {
                // 创建一级权限节点
                FunctionParent oneLevelFunction = new FunctionParent();
                oneLevelFunction.setChildren(new ArrayList<FunctionParent>());
                // 把当前遍历到的权限的信息赋值给一级权限节点
                BeanUtils.copyProperties(function, oneLevelFunction);
                // 一级权限集合添加该一级权限节点
                oneLevelFunctionList.add(oneLevelFunction);
            }
        }

        // 添加二级权限
        for (Function twoFunction : functionList) {
            for (FunctionParent oneLevelFunction : oneLevelFunctionList) {
                // 一级权限的节点的Id等于二级权限节点的pid
                if (oneLevelFunction.getId().equals(twoFunction.getParentId())) {
                    // 创建二级权限节点
                    FunctionParent twoLevelFunction = new FunctionParent();
                    twoLevelFunction.setChildren(new ArrayList<FunctionParent>());
                    // 将当前遍历到的权限赋值给二级权限节点
                    BeanUtils.copyProperties(twoFunction, twoLevelFunction);
                    // 将该二级权限节点放入到对应的一级权限节点的children集合中
                    oneLevelFunction.getChildren().add(twoLevelFunction);
                }
            }
        }

        // 添加三级权限
        for (Function threeFunction : functionList) {
            for (FunctionParent oneLevelFunction : oneLevelFunctionList) {
                List<FunctionParent> twoLevelFunctionList = oneLevelFunction.getChildren();
                for (FunctionParent twoLevelFunction : twoLevelFunctionList) {
                    if (twoLevelFunction.getId().equals(threeFunction.getParentId())) {
                        FunctionParent threeLevelFunction = new FunctionParent();
                        BeanUtils.copyProperties(threeFunction, threeLevelFunction);
                        twoLevelFunction.getChildren().add(threeLevelFunction);
                    }
                }
            }
        }
        return oneLevelFunctionList;
    }


    /**
     * 查询用户的所有权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<Function> findByUserId(String userId) {
//        List<Function> functionList = new ArrayList<>();
//        List<Role> roles = roleMapper.findByUserId(userId);
//        for (Role role : roles) {
//            functionList.addAll(functionMapper.findByRoleId(role.getId()));
//        }
        List<Function> functionLists = functionMapper.findByRoleIdByUserId(userId);
        return functionLists;
    }

    /**
     * 通过调用functionRoleService中的方法查找functionId并打入list
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Function> findThroughRoleIdFromFunctionRole(String roleId) {
        List<FunctionRole> functionRoles = functionRoleService.selectByRoleId(roleId);
        List<Function> functionList = null;
        for(FunctionRole functionRole : functionRoles) {
            String functionId = functionRole.getFunctionId();
            Function function = baseMapper.selectById(functionId);
            functionList.add(function);
        }
        return functionList;
    }

    /**
     * 查找未对该角色授权的权限
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Function> findOthersByRoleId(String roleId) {
        // 查询角色id是否存在
        roleService.findById(roleId);
        return functionMapper.findOthersByRoleId(roleId);
    }


    /**
     * 根据functionId查找
     *
     * @param functionId
     * @return
     */
    @Override
    public Function findById(String functionId) {
        Function function = baseMapper.selectById(functionId);
        return function;
    }

    /**
     * 给角色分配权限
     *
     * @param roleId
     * @param functionId
     */
    @Override
    public void saveRoleFunction(String roleId, String[] functionId) {

    }

    /**
     * 通过baseId和baseIdentity查找权限
     *
     * @param baseId
     * @param baseIdentity
     * @return
     */
    @Override
    public List<Function> findByBase(String baseId, Integer baseIdentity) {
//        List<Function> functionList = null;
//                List<BaseRoleFunction> baseRoleFunctionLists =
//                this.baseRoleFunctionService.
//                        findFunctionByBaseIdBaseIdentity(baseId, baseIdentity);
//        for (BaseRoleFunction baseRoleFunction : baseRoleFunctionLists) {
//            String functionId = baseRoleFunction.getFunctionId();
//            Function aFunction = baseMapper.selectById(functionId);
//            functionList.add(aFunction);
//        }
//        return functionList;
        List<Function> functionList = functionMapper.findByBaseIdByBaseIdentity(baseId, baseIdentity);
        return functionList;
    }

    /**
     * 基地老板更新基地角色的权限
     *
     * @param baseId
     * @param baseIdentity
     * @param functionIdList
     */
    @Override
    public void UpdateBaseFunOfRole(String baseId, Integer baseIdentity, Map functionIdList) {
        try {
            User user = userService.findByUserId(SecurityContextUtil.getUserDetails().getId());
            //查询执行操作的用户是否为基地老板 且同时验证角色id是否存在且该角色是否在老板基地中。
            if (!user.getBaseId().equals(baseId) || user.getBaseIdentity() != 2){
                throw new GlobalException(new Result(false, StatusCode.ERROR, "该用户不是基地老板，无法执行操作", null));
            }
            //判断base是否为空
            if(StringUtils.isEmpty(baseId) || StringUtils.isEmpty(baseIdentity)) {
                throw new GlobalException(new Result(false, StatusCode.ERROR, "未绑定基地或未授予基地身份，无法操作", null));
            }
            // 删除角色的所有权限
            baseRoleFunctionService.deleteALLBaseFunctionById(baseId, baseIdentity);

            List<Object> functionList = (List<Object>) functionIdList.get("functionIdList");
            for (Object functionId : functionList) {
                // 查询权限
                Function function = baseMapper.selectById((String) functionId);
                if (function == null && functionId != null) {
                    throw new GlobalException(new Result(false, StatusCode.ERROR, functionId + "权限不存在", null));
                }
                // 添加权限
                baseRoleFunctionService.addBaseRoleFunction(baseId, baseIdentity, (String) functionId);
            }
        } catch (Exception e) {
            throw new GlobalException(new Result(false, StatusCode.ERROR, "更新角色权限失败," + e.getMessage(), null));
        }
    }

    /**
     * 更新角色权限
     *
     * @param roleId
     * @param functionIdList
     */
    @Transactional
    @Async
    @Override
    public void updateFunctionOfRole(String roleId, Map functionIdList) {
        try {
//            // 查询角色
//            Role role = roleService.findById(roleId);
//            if (role == null) {
//                throw new GlobalException(new Result(false, StatusCode.ERROR, "角色不存在", null));
//            }
//            //拿到想赋值给角色的权限
//            List<Object> functionList = (List<Object>) functionIdList.get("functionIdList");
//            //如果为空，删掉角色所有权限并跳出
//            if (functionIdList == null || functionIdList.size() == 0){
//                roleMapper.deleteALLById(roleId);
//                return;
//            }
//            //想修改的权限的集合
//            Set<Object> modifiedSet = new HashSet<>(functionList);
//            //原有权限集合
//            Set<Object> originSet = new HashSet<>(functionRoleService.selectByRoleId(roleId));
//            //原来没有权限
//            if (originSet.isEmpty()){
//                for (Object functionId : functionList){
//                    Function function = baseMapper.selectById((String) functionId);
//                    if (function == null && functionId != null) {
//                        throw new GlobalException(new Result(false, StatusCode.ERROR, functionId + "权限不存在", null));
//                    }
//                    FunctionRole f = new FunctionRole();
//                    f.setRoleId(roleId);
//                    f.setFunctionId((String) functionId);
//                    functionRoleService.save(f);
////                    functionDao.addRoleFunction(roleId, (String) functionId);
//                }
//                return;
//            }
//            for (Object functionId : modifiedSet){
//                if (!originSet.contains(functionId)){
//                    // 查询权限
//                    Function function = baseMapper.selectById((String) functionId);
//                    if (function == null && functionId != null) {
//                        throw new GlobalException(new Result(false, StatusCode.ERROR, functionId + "权限不存在", null));
//                    }
//                    // 添加权限
//                    FunctionRole f = new FunctionRole();
//                    f.setRoleId(roleId);
//                    f.setFunctionId((String) functionId);
//                    functionRoleService.save(f);
////                    functionDao.addRoleFunction(roleId, (String) functionId);
//                }
//            }
//            for (Object functionId : originSet){
//                if (!modifiedSet.contains(functionId)){
//                    functionMapper.deleteFunctionByRoleId(functionId,roleId);
//                }
//            }
             //查询角色
            Role role = roleService.findById(roleId);
            if (role == null) {
                throw new GlobalException(new Result(false, StatusCode.ERROR, "角色不存在", null));
            }
            //拿到想赋值给角色的权限
            List<Object> functionList = (List<Object>) functionIdList.get("functionIdList");
            //删掉function_role表内role的所有权限
            roleMapper.deleteALLById(roleId);
            //如果为空，删掉角色所有权限并跳出
            if (functionIdList == null || functionIdList.size() == 0){
                return;
            }
            //想修改的权限的集合
            Set<Object> modifiedSet = new HashSet<>(functionList);
            for (Object functionId : modifiedSet){
                //根据functionId查找function
                Function function = baseMapper.selectById((String) functionId);
                if (function == null && functionId != null) {
                    throw new GlobalException(new Result(false, StatusCode.ERROR, functionId + "权限不存在", null));
                }
                FunctionRole f = new FunctionRole();
                f.setRoleId(roleId);
                f.setFunctionId((String) functionId);
                functionRoleService.save(f);
            }
        } catch (Exception e) {
            throw new GlobalException(new Result(false, StatusCode.ERROR, "更新角色权限失败," + e.getMessage(), null));
        }
    }

    @Override
    public List<Function> findByRoleId(String roleId) {
        // 查询角色id是否存在
        roleService.findById(roleId);
        return functionMapper.findByRoleId(roleId);
    }


//    @Override
//    public List<Function> findFunctionByBase(String userId, String baseId, String baseIdentity) {
//        if (userId == null) {
//            throw new GlobalException(StatusCode.ERROR, "用户不存在");
//        }
//        User user = userService.findByUserId(userId);
//        if (user == null){
//            throw new GlobalException(StatusCode.ERROR, "用户不存在");
//        }
//        //查询执行操作的用户是否为基地老板 且同时验证角色id是否存在且该角色是否在老板基地中。
//        if (!user.getBaseId().equals(baseId) || (user.getBaseIdentity() != "boss" && user.getBaseIdentity() != baseIdentity)){
//            throw new GlobalException(StatusCode.ERROR, "该用户不是基地老板，无法执行操作");
//        }
////        if (baseIdentity < 2){
////            throw new GlobalException(new Result(false, StatusCode.ERROR, "无法对该用户进行操作"));
////        }
////        if (baseIdentity == 2){
////            return findByUserId(user.getUserId());
////        }
////        return functionDao.findFunctionByBase(baseId,baseIdentity);
//    }
}
